import asyncio
import os
import sys
from pathlib import Path
from copilotkit import LangGraphAgent
from langfuse.langchain import CallbackHandler
from copilotkit.integrations.fastapi import add_fastapi_endpoint
# from app.core.logging import logger
from fastapi import FastAPI
import uvicorn


# 在设置环境变量之前检查当前工作目录和文件
print(f"当前工作目录: {os.getcwd()}")
print(f"当前文件: {__file__}")
print(f"sys.path:{sys.path}")

# 获取项目根目录（当前文件的上级目录的上级目录）
# 获取当前文件路径
current_file = Path(__file__)
project_root = current_file.parent.parent
print(f"项目根目录: {project_root}")

# 将项目根目录添加到sys.path的开头
sys.path.insert(0, str(project_root))
from app.core.logging import logger

from copilotkit import CopilotKitRemoteEndpoint
from ag_ui_langgraph import add_langgraph_fastapi_endpoint
from app.core.langgraph.sample_agent import SampleAgent
from dotenv import load_dotenv
os.environ["ENVIRONMENT"] = "development"
# 加载环境变量
load_dotenv()
print("langfuse=",os.getenv("LANGFUSE_SECRET_KEY"))
# 在Windows系统上解决psycopg与asyncio的兼容性问题
if sys.platform == 'win32':
    from asyncio import WindowsSelectorEventLoopPolicy

    asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())

# 创建FastAPI应用实例
app = FastAPI()

# 初始化SampleAgent并创建graph
# 异步初始化agent和graph
async def initialize_agent():
    # 初始化SampleAgent并创建graph
    agent_instance = SampleAgent()
    graph = await agent_instance.create_graph()
    mermaid = graph.get_graph().draw_mermaid()
    print(mermaid)
    return agent_instance, graph


# 在应用启动时初始化agent
@app.on_event("startup")
async def startup_event():
    global agent_instance, graph
    agent_instance, graph = await initialize_agent()
    print("初始化agent完成")
    print(type (graph))
    # 添加LangGraph端点到FastAPI应用
    sdk = CopilotKitRemoteEndpoint(
        agents=[
            LangGraphAgent(
                name="sample_agent",
                description="一个模拟智能体",
                graph=graph,
                langgraph_config={
                    "callbacks": [CallbackHandler()]
                }
            )
        ],
    )
    # add_langgraph_fastapi_endpoint(
    #     app=app,
    #     agent=LangGraphAGUIAgent(
    #         name="sample_agent",
    #         description="TiSmart Agent，用于处理用户请求",
    #         graph=graph,
    #     ),
    #     path="/copilotkit",
    # )
    history = await agent_instance.get_chat_history("session_001_fortest")
    print("history=",history)
    add_fastapi_endpoint(app, sdk, "/copilotkit")


# 在应用关闭事件中调用 shutdown 方法
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时清理资源"""
    # 关闭 SampleAgent 实例
    global agent_instance
    if agent_instance:  # 假设 sample_agent 是你的 SampleAgent 实例
        await agent_instance.shutdown()

    logger.info("应用已关闭，资源已清理")
# 添加健康检查路由
@app.get("/health")
def health():
    """健康检查函数，返回应用状态"""
    return {"status": "ok"}

# 定义主函数，用于运行uvicorn服务器
def main():
    """主函数，用于运行uvicorn服务器"""
    port = int(os.getenv("PORT", "8000"))
    uvicorn.run(
        "app.copilotkit_server:app",
        host="0.0.0.0",
        port=port,
        reload=True,
    )

if __name__ == "__main__":
    main()
